<template>
  <div class="app-container edit-page">
    <el-card shadow="never" class="box-card">
      <div slot="header" class="card-header">
        <span class="header-title">填报任务设置 需要加限制！！！待修改</span>
        <div class="header-actions">
          <el-button
            type="primary"
            :loading="buttonLoading"
            @click="submitForm2"
            v-if="form.dataStatus === 0 || form.dataStatus === 2"
          >提交
          </el-button>

          <el-button
            type="primary"
            :loading="buttonLoading"
            @click="submitForm1"
            v-if="form.dataStatus === 0 || form.dataStatus === 2"
          >保存
          </el-button>

          <el-button @click="submitBack">返回</el-button>
        </div>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">

          <!-- 任务名称 -->
          <el-col :span="8">
            <el-form-item label="任务名称" prop="taskName">
              <el-input v-model="form.taskName" placeholder="请输入任务名称"/>
            </el-form-item>
          </el-col>

          <!-- 填报对象 -->
          <el-col :span="8">
            <el-form-item label="填报对象" prop="reportObj">
              <el-select v-model="form.reportObj" placeholder="请选择填报对象" style="width:100%">
                <el-option
                  v-for="dict in dict.type.business_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 填报周期 -->
          <el-col :span="8">
            <el-form-item label="填报周期" prop="reportCycle">
              <el-select v-model="form.reportCycle" placeholder="请选择填报周期" style="width:100%">
                <el-option
                  v-for="dict in dict.type.filling_cycle"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数据采集周期" prop="reportCollectType">
              <el-select v-model="form.reportCollectType" placeholder="请选择数据采集周期" style="width:100%">
                <el-option
                  v-for="dict in dict.type.data_collect_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
              <div style="margin-top: 5px;color: #CCC4CC;font-size:12px">
                本周期:2025年6月发送的月度填报任务，视为采集2025年6月的数据
                <br>
                上一周期:2025年6月发送的月度填报任务，视为采集2025年5月的数据
              </div>
            </el-form-item>
          </el-col>

          <!-- 模板集合 -->
          <el-col :span="8">
            <el-form-item label="填报模板集合" prop="reportTemplate">
              <el-select
                v-model="tempReportTemplate"
                placeholder="请选择模板集合"
                style="width: 100%"
                multiple
                @change="handleReportTemplateChange"
              >
                <el-option label="园区信息" value="park"/>
                <el-option label="场站信息" value="station"/>
                <el-option label="场站运营信息" value="stationOp"/>
                <el-option label="物流企业信息" value="company"/>
                <el-option label="企业车辆信息" value="companyVehicles"/>
                <el-option label="企业仓储信息" value="companyStorage"/>
                <el-option label="企业专线信息" value="companyLine"/>
                <el-option label="企业运营信息" value="companyOp"/>
                <el-option
                  v-for="dict in dict.type.report_template"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>

              <div style="margin-top: 5px;">
                <el-button
                  type="text"
                  size="mini"
                  @click="previewTemplates"
                  :disabled="!tempReportTemplate.length"
                >
                  预览填报模板
                </el-button>
              </div>
            </el-form-item>
          </el-col>

          <!-- 推送时间 -->
          <el-col :span="8">
            <el-form-item label="推送时间" prop="sendDate">
              <!-- 临时 -->
              <template v-if="form.reportCycle === '1'">
                <el-radio-group v-model="form.sendType">
                  <el-radio label="immediate">立即发送</el-radio>
                  <el-radio label="timed">定时发送</el-radio>
                </el-radio-group>

                <div v-if="form.sendType === 'timed'" style="margin-top: 10px;">
                  <el-date-picker
                    v-model="form.sendDate"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择发送时间"
                    style="width: 100%;"
                  />
                </div>
              </template>

              <!-- 月度 -->
              <template v-else-if="form.reportCycle === '2'">
                <div style="display: flex; gap: 10px;">
                  <el-select v-model="form.sendDay" style="flex:1">
                    <el-option v-for="d in 28" :key="d" :label="d + '号'" :value="d"/>
                  </el-select>
                  <el-time-picker
                    v-model="form.sendTime"
                    placeholder="推送时间"
                    style="flex:1"
                    value-format="HH:mm:ss"
                    format="HH:mm:ss"
                  />
                </div>
                <div class="el-form-item__tip">每月自动推送</div>
              </template>

              <!-- 年度 -->
              <template v-else-if="form.reportCycle === '3'">
                <div style="display: flex; gap: 10px;">
                  <el-select v-model="form.sendMonth" style="flex:1">
                    <el-option v-for="m in 12" :key="m" :label="m + '月'" :value="m"/>
                  </el-select>
                  <el-select v-model="form.sendDay" style="flex:1">
                    <el-option v-for="d in 28" :key="d" :label="d + '号'" :value="d"/>
                  </el-select>
                  <el-time-picker
                    v-model="form.sendTime"
                    placeholder="推送时间"
                    style="flex:1"
                    value-format="HH:mm:ss"
                    format="HH:mm:ss"
                  />
                </div>
                <div class="el-form-item__tip">每年自动推送</div>
              </template>

              <template v-else>
                <el-input disabled placeholder="请先选择填报周期"/>
              </template>
            </el-form-item>
          </el-col>

          <!-- 有效期 -->
          <el-col :span="8">
            <el-form-item label="有效期(天)" prop="validityPeriod">
              <el-input-number :min="1" :max="30" controls-position="right"
                               v-model="form.validityPeriod" placeholder="请输入有效期"
              />
            </el-form-item>
          </el-col>

          <!-- 填报说明 -->
          <el-col :span="24">
            <el-form-item label="填报说明" prop="remark">
              <template #label>
                <span>填报说明</span>
                <el-tooltip class="item" effect="light" content="将会展示在用户的填写表单上，辅助用户进行表单填写"
                            placement="top">
                  <span><i class="el-icon-info"></i></span>
                </el-tooltip>
              </template>
              <el-input v-model="form.remark" type="textarea" :rows="3"/>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {getReportTask, addReportTask, updateReportTask} from '@/api/reportTask/reportTask'

export default {
  name: 'ReportTaskEdit',
  dicts: ['business_type', 'data_status_examine', 'filling_cycle', 'data_collect_type'],

  data() {
    return {
      buttonLoading: false,
      tempReportTemplate: [],
      form: {
        id: undefined,
        taskName: '',
        reportObj: '',
        reportCycle: '',
        reportCollectType: '',
        sendDate: null, // Date对象
        sendDateStr: '',
        validityPeriod: '',
        reportTemplate: '',
        dataStatus: 0,
        remark: '',
        sendType: 'immediate', // 临时发送类型
        sendDay: 1,
        sendMonth: 1,
        sendTime: '09:00:00',
        deadline: ''
      },
      rules: {
        taskName: [{required: true, message: '请输入任务名称', trigger: 'blur'}],
        reportObj: [{required: true, message: '请选择填报对象', trigger: 'blur'}],
        reportCycle: [{required: true, message: '请选择填报周期', trigger: 'blur'}],
        reportCollectType: [{required: true, message: '请选择数据采集周期', trigger: 'blur'}],
        validityPeriod: [{required: true, message: '请填写有效期', trigger: 'blur'}]
      }
    }
  },

  watch: {
    'form.validityPeriod': 'calcDeadline',
    'form.sendDate': 'calcDeadline',
    'form.sendDay': 'calcDeadline',
    'form.sendMonth': 'calcDeadline',
    'form.sendTime': 'calcDeadline',
    'form.sendType': 'calcDeadline',
    'form.reportCycle'(val) {
      if (val === '1' && !this.form.sendType) this.form.sendType = 'immediate'
      if (val === '2') {
        if (!this.form.sendDay) this.form.sendDay = 1
        if (!this.form.sendTime) this.form.sendTime = '09:00:00'
      }
      if (val === '3') {
        if (!this.form.sendMonth) this.form.sendMonth = 1
        if (!this.form.sendDay) this.form.sendDay = 1
        if (!this.form.sendTime) this.form.sendTime = '09:00:00'
      }
    }
  },

  created() {
    const id = this.$route.query.id
    if (id) this.loadData(id)
  },

  methods: {

    async loadData(id) {
      try {
        const res = await getReportTask(id)
        const data = res.data
        this.tempReportTemplate = data.reportTemplate ? data.reportTemplate.split(',') : []

        this.form = {...this.form, ...data}

        // --- 临时一次发送回显 ---
        if (data.reportCycle === '1') {
          this.form.sendType = data.sendDate ? 'timed' : 'immediate'
          if (data.sendDate) {
            const parts = data.sendDate.split(/[- :]/)
            this.form.sendDate = new Date(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5])
          }
        }

        // --- 月度 ---
        if (data.reportCycle === '2') {
          this.form.sendDay = data.sendDay || 1
          this.form.sendTime = data.sendTime || '09:00:00'
        }

        // --- 年度 ---
        if (data.reportCycle === '3') {
          this.form.sendMonth = data.sendMonth || 1
          this.form.sendDay = data.sendDay || 1
          this.form.sendTime = data.sendTime || '09:00:00'
        }

        console.log("111", this.form)
        this.calcDeadline()
      } catch {
        this.$message.error('加载失败')
      }
    },

    calcDeadline() {
      const now = new Date()
      let sendDateObj = null

      if (this.form.reportCycle === '1') {
        if (this.form.sendType === 'immediate') sendDateObj = new Date()
        else if (this.form.sendDate) sendDateObj = new Date(this.form.sendDate)
      } else if (this.form.reportCycle === '2') {
        sendDateObj = new Date(now.getFullYear(), now.getMonth(), this.form.sendDay)
        if (this.form.sendTime) {
          const [h, m, s] = this.form.sendTime.split(':')
          sendDateObj.setHours(h, m, s)
        }
      } else if (this.form.reportCycle === '3') {
        sendDateObj = new Date(now.getFullYear(), this.form.sendMonth - 1, this.form.sendDay)
        if (this.form.sendTime) {
          const [h, m, s] = this.form.sendTime.split(':')
          sendDateObj.setHours(h, m, s)
        }
      }

      if (sendDateObj && this.form.validityPeriod) {
        const d = new Date(sendDateObj)
        d.setDate(d.getDate() + Number(this.form.validityPeriod))
        this.form.deadline = d.toISOString().split('T')[0]
      } else {
        this.form.deadline = ''
      }
    },

    handleReportTemplateChange(val) {
      this.form.reportTemplate = val.join(',')
    },

    buildSendDateStr() {
      if (this.form.reportCycle === '1') {
        if (this.form.sendType === 'immediate') this.form.sendDateStr = '一次发送'
        else if (this.form.sendDate) this.form.sendDateStr = `一次发送: ${this.form.sendDate.toISOString().slice(0, 19).replace('T', ' ')}`
      } else if (this.form.reportCycle === '2') {
        this.form.sendDateStr = `每月${this.form.sendDay}号定时发送`
      } else if (this.form.reportCycle === '3') {
        this.form.sendDateStr = `每年${this.form.sendMonth}月${this.form.sendDay}号定时发送`
      }
    },

    submitForm1() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        this.buttonLoading = true
        try {
          this.buildSendDateStr()
          this.form.dataStatus = 0
          if (this.form.id) await updateReportTask(this.form)
          else await addReportTask(this.form)
          this.$message.success('保存成功')
          this.submitBack()
        } catch {
          this.$message.error('保存失败')
        } finally {
          this.buttonLoading = false
        }
      })
    },

    submitForm2() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        this.buttonLoading = true
        try {
          this.buildSendDateStr()
          this.form.dataStatus = 3
          if (this.form.id) await updateReportTask(this.form)
          else await addReportTask(this.form)
          this.$message.success('提交成功')
          this.submitBack()
        } catch {
          this.form.dataStatus = 0
          this.$message.error('提交失败')
        } finally {
          this.buttonLoading = false
        }
      })
    },

    submitBack() {
      this.$tab.closeOpenPage({path: '/reportTask/reportTask'})
    },

    previewTemplates() {
      const templates = this.tempReportTemplate
      if (!templates.length) return
      const params = new URLSearchParams({
        titleYear: this.form.sendDate ? this.form.sendDate.getFullYear() + '年' : '',
        titleName: this.form.taskName,
        helperText: this.form.remark,
        deadline: this.form.deadline,
        reportTemplate: templates.join(','),
        isPreview: true
      }).toString()
      window.open(`/report/previewFill/reportFill?${params}`, '_blank')
    }
  }
}
</script>


<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.box-card {
  border-radius: 8px;
  border: 1px solid #e6e8eb;
}

.tip-show {
  color: red;
  font-weight: bold;
  font-size: 14px;
}
</style>
